// ==UserScript==
// @name         B站播放器宽度控制器
// @namespace    http://tampermonkey.net/
// @version      1.1
// @description  控制B站播放器容器的宽度
// @author       You
// @match        *://*.bilibili.com/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    let isInitialized = false;
    let retryCount = 0;
    const MAX_RETRIES = 20;

    // 安全的等待元素函数，使用更短的间隔和更少的重试
    function waitForElement(selector, callback, maxTries = 20) {
        if (maxTries <= 0) {
            console.log('等待元素超时:', selector);
            return;
        }
        
        const element = document.querySelector(selector);
        if (element) {
            callback(element);
        } else {
            // 使用更短的间隔，避免阻塞
            setTimeout(() => waitForElement(selector, callback, maxTries - 1), 200);
        }
    }

    // 创建控制面板
    function createControlPanel() {
        // 检查是否已经存在面板
        if (document.getElementById('bilibili-player-width-panel')) {
            return;
        }

        const panel = document.createElement('div');
        panel.id = 'bilibili-player-width-panel';
        panel.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            width: 200px;
            background: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 15px;
            border-radius: 8px;
            font-family: 'Microsoft YaHei', sans-serif;
            z-index: 9999;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
            transition: all 0.3s ease;
            overflow: hidden;
            min-height: 50px;
        `;

        panel.innerHTML = `
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                <div style="font-weight: bold;">🎮 播放器控制</div>
                <button id="collapse-panel" style="background: none; border: none; color: white; cursor: pointer; font-size: 16px; padding: 0; width: 20px; height: 20px; display: flex; align-items: center; justify-content: center;">
                    ▲
                </button>
            </div>
            <div class="panel-content">
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-size: 12px;">
                        当前尺寸: <span id="current-width">--</span> × <span id="current-height">--</span>px
                    </label>
                    <input type="range" id="width-slider" min="20" max="800" value="400" 
                           style="width: 100%; height: 6px; border-radius: 3px; outline: none;">
                    <div style="display: flex; justify-content: space-between; font-size: 10px; margin-top: 5px;">
                        <span>20px</span>
                        <span>800px</span>
                    </div>
                </div>
                <div style="margin-bottom: 10px;">
                    <button id="reset-width" style="width: 100%; padding: 8px; background: #00a1d6; border: none; color: white; border-radius: 4px; cursor: pointer; font-weight: bold;">
                        重置尺寸
                    </button>
                </div>
                <div style="display: flex; gap: 5px;">
                    <button id="focus-mode" style="width: 100%; padding: 8px; background: #ff6b6b; border: none; color: white; border-radius: 4px; cursor: pointer; font-weight: bold;">
                        🎯 专注模式
                    </button>
                </div>
            </div>
        `;

        document.body.appendChild(panel);
        
        // 添加收起状态和专注模式的CSS样式
        const style = document.createElement('style');
        style.textContent = `
            #bilibili-player-width-panel.collapsed {
                padding: 10px;
                display: flex;
                align-items: center;
                justify-content: center;
            }
            #bilibili-player-width-panel.collapsed .panel-content {
                display: none;
            }
            #bilibili-player-width-panel.collapsed #collapse-panel {
                margin: 0;
            }
            
            /* 专注模式样式 */
            body.focus-mode-active .bpx-player-container {
                margin: 0 auto !important;
            }
            
            body.focus-mode-active .bpx-player-container .bpx-player-video-wrap {
                border-radius: 8px;
                overflow: hidden;
            }
            
            /* 确保退出专注模式时能正确还原 */
            .bpx-player-container {
                transition: margin 0.3s ease;
            }
        `;
        document.head.appendChild(style);

        // 绑定事件
        const slider = panel.querySelector('#width-slider');
        const resetBtn = panel.querySelector('#reset-width');
        const focusBtn = panel.querySelector('#focus-mode');
        const collapseBtn = panel.querySelector('#collapse-panel');
        const currentWidthSpan = panel.querySelector('#current-width');

        // 滑块控制宽度
        slider.addEventListener('input', function() {
            const width = this.value;
            const height = Math.round(width * 9 / 16);
            setPlayerWidth(width);
            currentWidthSpan.textContent = width;
            currentHeightSpan.textContent = height;
        });

        // 重置按钮
        resetBtn.addEventListener('click', function() {
            slider.value = 400;
            const height = Math.round(400 * 9 / 16);
            setPlayerWidth(400);
            currentWidthSpan.textContent = '400';
            currentHeightSpan.textContent = height;
        });

        // 专注模式按钮
        focusBtn.addEventListener('click', function() {
            toggleFocusMode();
        });

        // 收起/展开面板
        collapseBtn.addEventListener('click', function() {
            toggleCollapse();
        });

        // 初始化当前宽度显示
        updateCurrentWidth();
    }

    // 设置播放器宽度和高度（16:9比例）
    function setPlayerWidth(width) {
        const playerContainer = document.querySelector('.bpx-player-container');
        if (playerContainer) {
            // 计算16:9比例的高度
            const height = Math.round(width * 9 / 16);
            
            playerContainer.style.width = width + 'px';
            playerContainer.style.height = height + 'px';
            playerContainer.style.minWidth = width + 'px';
            playerContainer.style.maxWidth = width + 'px';
            playerContainer.style.minHeight = height + 'px';
            playerContainer.style.maxHeight = height + 'px';
            
            // 保存到localStorage
            try {
                localStorage.setItem('bilibili-player-width', width);
            } catch (e) {
                console.log('保存设置失败:', e);
            }
        }
    }

    // 更新当前尺寸显示
    function updateCurrentWidth() {
        const playerContainer = document.querySelector('.bpx-player-container');
        const currentWidthSpan = document.querySelector('#current-width');
        const currentHeightSpan = document.querySelector('#current-height');
        if (playerContainer && currentWidthSpan && currentHeightSpan) {
            const currentWidth = playerContainer.style.width || '400';
            const widthValue = currentWidth.replace('px', '');
            const heightValue = Math.round(widthValue * 9 / 16);
            
            currentWidthSpan.textContent = widthValue;
            currentHeightSpan.textContent = heightValue;
            
            // 同步滑块值
            const slider = document.querySelector('#width-slider');
            if (slider) {
                slider.value = widthValue;
            }
        }
    }

    // 从localStorage恢复宽度设置
    function restoreWidthSetting() {
        try {
            const savedWidth = localStorage.getItem('bilibili-player-width');
            if (savedWidth) {
                setPlayerWidth(savedWidth);
            }
        } catch (e) {
            console.log('读取设置失败:', e);
        }
    }

    // 专注模式切换
    function toggleFocusMode() {
        const focusBtn = document.querySelector('#focus-mode');
        const isHidden = document.body.classList.contains('focus-mode-active');
        
        if (isHidden) {
            // 显示所有元素
            showAllElements();
            // 强制刷新页面布局
            forceLayoutRefresh();
            focusBtn.textContent = '🎯 专注模式';
            focusBtn.style.background = '#ff6b6b';
            document.body.classList.remove('focus-mode-active');
            
            // 保存状态到localStorage
            try {
                localStorage.setItem('bilibili-focus-mode', 'false');
            } catch (e) {
                console.log('保存专注模式状态失败:', e);
            }
        } else {
            // 隐藏干扰元素
            hideDistractingElements();
            focusBtn.textContent = '🔓 退出专注';
            focusBtn.style.background = '#28a745';
            document.body.classList.add('focus-mode-active');
            
            // 保存状态到localStorage
            try {
                localStorage.setItem('bilibili-focus-mode', 'true');
            } catch (e) {
                console.log('保存专注模式状态失败:', e);
            }
        }
    }

    // 强制刷新页面布局
    function forceLayoutRefresh() {
        // 触发重排和重绘
        document.body.offsetHeight;
        
        // 延迟执行，确保DOM更新完成
        setTimeout(() => {
            // 重新计算播放器位置
            const playerContainer = document.querySelector('.bpx-player-container');
            if (playerContainer) {
                playerContainer.style.margin = '';
                // 触发一次重排
                playerContainer.offsetHeight;
            }
        }, 100);
    }

    // 隐藏干扰元素
    function hideDistractingElements() {
        const elementsToHide = [
            '.right-container',           // 右侧推荐
            '#commentapp',                // 评论区
            '.bpx-player-sending-area',  // 播放器发送区域
            '#biliMainHeader',           // 主头部
            '#arc_toolbar_report',       // 视频工具栏
            '#v_desc',                   // 视频描述
            '.video-tag-container',      // 视频标签
            '.activity-m-v1.act-now'    // 活动标签
        ];
        
        elementsToHide.forEach(selector => {
            const elements = document.querySelectorAll(selector);
            elements.forEach(element => {
                if (element) {
                    // 保存原始display值，包括计算样式
                    if (!element.dataset.originalDisplay) {
                        const computedStyle = window.getComputedStyle(element);
                        const originalDisplay = element.style.display || computedStyle.display || '';
                        element.dataset.originalDisplay = originalDisplay;
                    }
                    element.style.display = 'none';
                }
            });
        });
    }

    // 显示所有元素
    function showAllElements() {
        const elementsToShow = [
            '.right-container',
            '#commentapp',
            '.bpx-player-sending-area',
            '#biliMainHeader',
            '#arc_toolbar_report',
            '#v_desc',
            '.video-tag-container',
            '.activity-m-v1.act-now'
        ];
        
        elementsToShow.forEach(selector => {
            const elements = document.querySelectorAll(selector);
            elements.forEach(element => {
                if (element) {
                    // 如果有保存的原始值，使用它；否则使用默认值
                    if (element.dataset.originalDisplay !== undefined) {
                        element.style.display = element.dataset.originalDisplay;
                    } else {
                        // 根据元素类型设置默认display值
                        const tagName = element.tagName.toLowerCase();
                        if (tagName === 'div' || tagName === 'section' || tagName === 'header') {
                            element.style.display = 'block';
                        } else if (tagName === 'span' || tagName === 'a') {
                            element.style.display = 'inline';
                        } else {
                            element.style.display = '';
                        }
                    }
                }
            });
        });
    }

    // 恢复专注模式状态
    function restoreFocusMode() {
        try {
            const focusMode = localStorage.getItem('bilibili-focus-mode');
            if (focusMode === 'true') {
                const focusBtn = document.querySelector('#focus-mode');
                
                if (focusBtn) {
                    // 隐藏干扰元素
                    hideDistractingElements();
                    focusBtn.textContent = '🔓 退出专注';
                    focusBtn.style.background = '#28a745';
                    document.body.classList.add('focus-mode-active');
                    
                    // 确保播放器居中
                    const playerContainer = document.querySelector('.bpx-player-container');
                    if (playerContainer) {
                        playerContainer.style.margin = '0 auto';
                    }
                }
            }
        } catch (e) {
            console.log('恢复专注模式状态失败:', e);
        }
    }

    // 收起/展开面板
    function toggleCollapse() {
        const panel = document.getElementById('bilibili-player-width-panel');
        const collapseBtn = document.querySelector('#collapse-panel');
        const content = panel.querySelector('.panel-content');
        
        if (panel.classList.contains('collapsed')) {
            // 展开面板
            panel.classList.remove('collapsed');
            panel.style.width = '200px';
            panel.style.height = 'auto';
            collapseBtn.textContent = '▲';
            collapseBtn.title = '收起面板';
            
            // 保存状态到localStorage
            try {
                localStorage.setItem('bilibili-panel-collapsed', 'false');
            } catch (e) {
                console.log('保存面板状态失败:', e);
            }
        } else {
            // 收起面板
            panel.classList.add('collapsed');
            panel.style.width = '50px';
            panel.style.height = '50px';
            collapseBtn.textContent = '▼';
            collapseBtn.title = '展开面板';
            
            // 保存状态到localStorage
            try {
                localStorage.setItem('bilibili-panel-collapsed', 'true');
            } catch (e) {
                console.log('保存面板状态失败:', e);
            }
        }
    }

    // 恢复面板收起状态
    function restorePanelState() {
        try {
            const collapsed = localStorage.getItem('bilibili-panel-collapsed');
            if (collapsed === 'true') {
                const panel = document.getElementById('bilibili-player-width-panel');
                const collapseBtn = document.querySelector('#collapse-panel');
                
                if (panel && collapseBtn) {
                    panel.classList.add('collapsed');
                    panel.style.width = '50px';
                    panel.style.height = '50px';
                    collapseBtn.textContent = '▼';
                    collapseBtn.title = '展开面板';
                }
            }
        } catch (e) {
            console.log('恢复面板状态失败:', e);
        }
    }

    // 简化的初始化函数
    function init() {
        if (isInitialized) {
            return;
        }

        // 检查是否在B站页面
        if (!window.location.hostname.includes('bilibili.com')) {
            return;
        }

        // 等待播放器容器加载，使用更保守的策略
        waitForElement('.bpx-player-container', function(playerContainer) {
            if (isInitialized) {
                return;
            }

            try {
                // 创建控制面板
                createControlPanel();
                
                // 恢复保存的宽度设置
                restoreWidthSetting();
                
                // 恢复专注模式状态
                setTimeout(() => {
                    restoreFocusMode();
                }, 100);
                
                // 恢复面板收起状态
                setTimeout(() => {
                    restorePanelState();
                }, 150);
                
                isInitialized = true;
                console.log('B站播放器宽度控制器已加载');
            } catch (e) {
                console.error('初始化失败:', e);
            }
        });
    }

    // 使用更安全的加载策略
    function safeInit() {
        // 延迟初始化，避免阻塞页面加载
        setTimeout(() => {
            if (document.readyState === 'complete') {
                init();
            } else {
                // 如果页面还没完全加载，等待更长时间
                setTimeout(init, 1000);
            }
        }, 500);
    }

    // 监听页面变化，处理SPA路由
    function observePageChanges() {
        let lastUrl = location.href;
        
        // 使用更轻量的方式监听URL变化
        const observer = new MutationObserver(function() {
            if (location.href !== lastUrl) {
                lastUrl = location.href;
                // URL变化后重置状态
                isInitialized = false;
                retryCount = 0;
                // 延迟重新初始化
                setTimeout(safeInit, 500);
            }
        });

        observer.observe(document.body, {
            childList: true,
            subtree: false
        });
    }

    // 主入口
    function main() {
        try {
            // 立即开始观察页面变化
            observePageChanges();
            
            // 安全初始化
            safeInit();
            
        } catch (e) {
            console.error('脚本运行错误:', e);
        }
    }

    // 启动脚本
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', main, { once: true });
    } else {
        main();
    }

})();
